#!/usr/bin/env node

const { program } = require('commander');
const inquirer = require('inquirer');
const chalk = require('chalk');
const fs = require('fs-extra');
const path = require('path');
const { execSync } = require('child_process');

program
  .version('0.1.0')
  .command('create <project-name>')
  .description('create a new project')
  .action(async (projectName) => {
    const answers = await inquirer.prompt([
      {
        type: 'list',
        name: 'preset',
        message: 'Please pick a preset:',
        choices: [
          { name: 'Default (MiniApp + Router + Store)', value: 'default' },
          { name: 'Manually select features', value: 'manual' }
        ]
      },
      {
        type: 'checkbox',
        name: 'features',
        message: 'Check the features needed for your project:',
        choices: [
          { name: 'Router', value: 'router' },
          { name: 'Store', value: 'store' },
          { name: 'CSS Pre-processors', value: 'css' }
        ],
        when: (answers) => answers.preset === 'manual'
      },
      {
        type: 'list',
        name: 'cssPreprocessor',
        message: 'Pick a CSS pre-processor:',
        choices: [
          { name: 'Sass/SCSS', value: 'sass' },
          { name: 'Less', value: 'less' },
          { name: 'Stylus', value: 'stylus' }
        ],
        when: (answers) => answers.features && answers.features.includes('css')
      }
    ]);

    console.log(chalk.blue('Creating project...'));
    const templateDir = path.join(__dirname, 'template');
    const projectDir = path.join(process.cwd(), projectName);

    fs.copySync(templateDir, projectDir);

    const packageJson = require(path.join(projectDir, 'package.json'));
    packageJson.name = projectName;

    if (answers.preset === 'manual') {
      if (!answers.features.includes('router')) {
        delete packageJson.dependencies['mini-router'];
      }
      if (!answers.features.includes('store')) {
        delete packageJson.dependencies['mini-store'];
      }
      if (answers.features.includes('css')) {
        packageJson.devDependencies[answers.cssPreprocessor] = '^1.0.0';
      }
    }

    fs.writeFileSync(
      path.join(projectDir, 'package.json'),
      JSON.stringify(packageJson, null, 2)
    );

    console.log(chalk.blue('Installing dependencies...'));
    execSync('npm install', { cwd: projectDir, stdio: 'inherit' });

    console.log(chalk.green(`
Project ${projectName} created successfully!
To get started:

  cd ${projectName}
  npm run serve
`));
  });

program.parse(process.argv);